// ----------------------------------------------------------- //
// First HTML5 / Canvas Game.
// Spy Runner 
// Run and avoid the obstacle.
// Coded by tibone
// tibone@gmail.com
// http://www.classicgames.com.br/spyrunner
// Source Code at : http://code.google.com/p/spyrunner/
// ----------------------------------------------------------- //


// Creates the Gamebox (Canvas)
	var gamebox = document.getElementById('gamebox'); // Sets the Canvas Element. (Used here only as a reference, because we will have to re-write this var in every funcion).
//

// Sets somes variables
	gameSpeed = 4; // All scrolling objects will be attached to this object
	playerSpeed = 7; // How many pixels the player scrolls sideways
	level = 1; // Start at Level 1, obviously.
	var enemyYPos = [];	// Used to track enemies
    var enemyXPos = [];   // Used to Track enemies
	alive = 0; // Are we alive ?
	score = 0; // We don't have any points.
	hiscore = localStorage.getItem("spyrunner.hiscore"); // Fetches the highest score from the save
	music = new Audio("snd/spyrunner.ogg");
//

// Used for Scrolling the Central White Lines
	cScroll = -72;
//


// Creates the Player Element
	var player = new Image();
	player.src = "img/player.png"; // Player sprite
	var playerX = 50; // Player X position
	var playerY = 290; // Player Y position
//

// Creates the background Elements
	var bg = new Image();
	bg.src = "img/background.jpg"; // Background Image
	var title = new Image(); 
	title.src = "img/title.jpg"; // Title Screen
	var gameover = new Image();
	gameover.src = "img/gameover.jpg"; // Gameover Screen
//	

// Creates the White Lines that Scrolls vertically
	var wline = new Image();
	wline.src = "img/wline.jpg" // White Line Image
	wScroll = -10; // var to Scroll the Lines //
//

// The "cracks on the road" element
	var rcrack = new Image();
	rcrack.src = "img/road_crack.png"
	rScroll = -70; 
//

// Creates the Enemy Element
	var enemy1 = new Image();
	enemy1.src = "img/enemy1.png" // Enemy Sprite
	var enemyX = 0;
	var enemyY = 0;
//

// The function that is ran when the user clicks the canvas.
	function start() { 
		var gamebox = document.getElementById('gamebox'); // Sets the Canvas Element.
		gamebox.width = 320;
		gamebox.height = 320;
		window.onkeydown = keyControl; // Sets that the function keyControl will catch and handle all the keypress
		alive = 1;
		playMusic();
		
		setInterval(loop, 30); // This starts the main loop of the game, which is called every 30ms (about 30fps).
				
	}
//

// After loading, this is our main loop
	function loop() {
		var gamebox = document.getElementById('gamebox'); // Sets the Canvas Element.
		
		
		
		// Clear the screen
		gamebox.width = 320;
		
		if(alive == 1) {
			// Check the Current Level we're playing in 
			checkLevel();
			
			// Draws the background
			gamebox.getContext("2d").drawImage(bg, 0, 0);
		
			// Scroll the White Lines
			bgAnim(); // Animates the background
			
			//Update the Player
			updatePlayer();
			
			//Updates Enemies
			updateEnemies();
			
			// Draw Score
			drawScore();
						
		}
		
		// If we're dead, then go to the GameOver Screen
		if(alive == 0) {
			GameOverScreen();
		}
	}
//

// This function changes the Player X and Y, according to the keyboard
function keyControl(e) {
	// Move the player to the left
	if(e.keyCode == 37) { 
		if(playerX > 25) {
			playerX = playerX - playerSpeed;
		}
	}

	// Key pressed is Right Arrow
	if(e.keyCode == 39) {
		//bgScroll = bgScroll - 5; // Scroll the background to the right.
		if(playerX < 280) {
			playerX = playerX + playerSpeed;
		}
	}

}

// Updates the player Accordingly to the Key Strokes.
function updatePlayer() { 
		var gamebox = document.getElementById('gamebox'); // Sets the Canvas Element.
		    
		// Set the current position of the player, based on the keyboard
		gamebox.getContext("2d").drawImage(player, playerX, playerY); // Draw the player on the screen
}

// Draws and Scroll the enemies
function updateEnemies() {
			var gamebox = document.getElementById('gamebox'); // Sets the Canvas Element.
			var sndPass = new Audio("snd/passing.ogg"); // Sets the sound element.
		
			
			var currentEnemyNumber = 0; // Clears the var, for the loop
			var numberOfEnemies = enemyXPos.length; // The number of the Enemies is as long as the array
	
			// We have a one in 40 chance of an enemy being created.
			if (Math.random() < 1/40)
			{
				enemyYPos.push(-100);
				enemyXPos.push(Math.random() * 300);
			}
			
			// Checks the number of enemies and moves the Y position according to the gamespeed.
			while (currentEnemyNumber < numberOfEnemies) {
				enemyYPos[currentEnemyNumber] = enemyYPos[currentEnemyNumber] + gameSpeed;
				currentEnemyNumber = currentEnemyNumber + 1;
			}
			
			// Draw the enemies and if they're in the right spot, play the sound.
			currentEnemyNumber = 0;
			while (currentEnemyNumber < numberOfEnemies) {
				gamebox.getContext("2d").drawImage(enemy1, enemyXPos[currentEnemyNumber], enemyYPos[currentEnemyNumber]);
				
				if(enemyYPos[currentEnemyNumber] == 320) {
					sndPass.play();
				}
				
				// Checks if the player and enemy are occuping the same space (colliding), if so, then you dead, bro
				if ( ( (playerX < enemyXPos[currentEnemyNumber] && enemyXPos[currentEnemyNumber] < playerX + 18) || (enemyXPos[currentEnemyNumber] < playerX && playerX < enemyXPos[currentEnemyNumber] + 30) ) && ( (playerY < enemyYPos[currentEnemyNumber] && enemyYPos[currentEnemyNumber] < playerY + 33) || (enemyYPos[currentEnemyNumber] < playerY && playerY < enemyYPos[currentEnemyNumber] + 30) ) ) {
					alive = 0;
				}
								
				// Increases the enemy number
				currentEnemyNumber = currentEnemyNumber + 1;
			}
			
}
	

// Animates the background
function bgAnim() { 
		var gamebox = document.getElementById('gamebox'); // Sets the Canvas element.
		
		gamebox.getContext("2d").drawImage(wline, 0, wScroll); // Draw the left line;
		gamebox.getContext("2d").drawImage(wline, 306, wScroll); // Draw the right line;
		
		gamebox.getContext("2d").drawImage(wline, 0, wScroll - 200); // Draw the Secondary Left Line;
		gamebox.getContext("2d").drawImage(wline, 306, wScroll - 200); // Draw the Secondary Left Line;
		
		gamebox.getContext("2d").drawImage(wline, 106, cScroll); // Draws the Left Central Line
		gamebox.getContext("2d").drawImage(wline, 212, cScroll); // Draws the Right Central Line
		
		gamebox.getContext("2d").drawImage(wline, 106, cScroll - 200); // Draws the Left Central Line
		gamebox.getContext("2d").drawImage(wline, 212, cScroll - 200); // Draws the Right Central Line
		
		gamebox.getContext("2d").drawImage(rcrack, 0, rScroll); // Draw the cracks in the road
				
		cScroll = cScroll + gameSpeed; // Changes the Y position of the element, according to the current speed. (Central Lines)
		wScroll = wScroll + gameSpeed; // Changes the Y Position of the element. (Curbs)
		rScroll = rScroll + gameSpeed; // Change the Y position of the element. (road crack);
		
		// If the Lines are Out of the screen, then go back up
		if(wScroll > 520) { 
			wScroll = -74;
		}
		
		// If the Lines are out of the screen, then go back up
		if(cScroll > 592) {
			cScroll = -74;
		}
		
		// If the Lines are out of the screen, then go back up
		if(rScroll > 320) {
			rScroll = -320;
		}
		
}

// Game Over Yeaaaaah
function GameOverScreen() { 
	var gamebox = document.getElementById('gamebox'); // Sets the Canvas element.
	if(score > hiscore) { 
		localStorage.setItem("spyrunner.hiscore", score); // If we have set a new highscore, then we save it.
	}
	music.loop = false; // Stop looping the music
	music.pause(); // Pauses the Music, because stop is not implemented.
	gamebox.getContext("2d").drawImage(gameover, 0,0);
	gamebox.getContext("2d").fillStyle = "#FFFFFF";
	gamebox.getContext("2d").fillText("GAME OVER", 100,160);
	gamebox.getContext("2d").fillText("Press F5 to Try Again", 100, 180);
	gamebox.getContext("2d").fillText("Hi-Score : " + hiscore, 100, 10);
}

// Draw Score 
function drawScore() { 
	var gamebox = document.getElementById('gamebox'); // Sets the Canvas element.

	score = score + 1; // The score increases by 1 each 30 miliseconds.
	
	// Sets the font and draws the score.
	gamebox.getContext("2d").font = "12px VT323";
	gamebox.getContext("2d").fillStyle = "#FFFFFF";
	gamebox.getContext("2d").textBaseline = "top";
	gamebox.getContext("2d").fillText("Score: " + score, 20, 10);

	gamebox.getContext("2d").fillText("Hi-Score : " + hiscore, 170, 10);
	
}

// Check the game level
function checkLevel() {

//Based on how long we are alive (score), we set the game speed.
	switch(score)
		{
			case 1000:
			playerSpeed = 8;
			gameSpeed = 6;
			level = 2;
			break;
			
			case 2000:
			playerSpeed = 8;
			gameSpeed = 8;
			level = 3;
			break;
			
			case 3000:
			playerSpeed = 8;
			gameSpeed = 10;
			level = 4;
			break;
			
			case 4000:
			playerSpeed = 8;
			gameSpeed = 12;
			level = 5;
			break;
			
			case 5000:
			playerSpeed = 8;
			gameSpeed = 14;
			level = 6;
			break;
			
			case 6000:
			playerSpeed = 8;
			gameSpeed = 16;
			level = 7;
			break;
			
			case 7000:
			playerSpeed = 8;
			gameSpeed = 18;
			level = 8;
			break;
			
			case 8000:
			playerSpeed = 8;
			gameSpeed = 20;
			level = 9;
			break;
					
		}
	
	
}

// Used to play the music.
function playMusic() {
	// The Following Method don't work in Firefox, only Chrome so it's commented out.
	//music.loop = true;
	//music.play();
	
	//This method works in Firefox, Chrome and Opera (haven't tested on Safari)
	//Unfortunately it is a lot bigger, 5 lines instead of 2.
	music.addEventListener('ended', function() {
		this.currentTime = 0;
		this.play();
	}, false);
	music.play();
}

// Used to display the title Screen.
function title_screen() { 
	var gamebox = document.getElementById('gamebox'); // Sets the Canvas element.
	gamebox.width = 320;
	gamebox.height = 320;
	gamebox.getContext("2d").drawImage(title, 0,0);
	gamebox.getContext("2d").fillStyle = "#FFFFFF";
	gamebox.getContext("2d").fillText("Hi-Score : " + hiscore, 100, 10);
}